import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class XcxStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['sortWeight;desc'],
      size: 10,
    },
  };
  total = 0;
  xcx = [];
  modal = [];
  city = [];
  fromCity = [];
  toCity = [];
  scStartStation = [];
  scEndStation = [];
  startStation = [];
  endStation = [];
  ccStartStation = [];
  ccEndStation = [];
  iconUrls = [];
  loading = false;
  _orderStatus = '0';

  _APIS = {
    0: { search: api.search, count: api.count },
    1: { search: api.search, count: api.count },
    2: { search: api.search, count: api.count },
    3: { search: api.search, count: api.count },
    5: { search: api.dictSearch, count: api.dictCount },
    6: { search: api.entryLogo, count: api.entryLogoCount },
  }

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (this._orderStatus !== '5' || this._orderStatus !== '6') {
      if (this._orderStatus === '3') {
        search.type = '4';
        search.entryType = '0';
      } else {
        search.entryType = this._orderStatus;
      }
    }
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield this._APIS[this._orderStatus].count({ search });
      this.xcx = yield this._APIS[this._orderStatus].search({ search, pg });
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * update(announce) {
    yield api.update(announce);
    yield this.query();
  }

  * create(announce) {
    yield api.create(announce);
    yield this.query();
  }

  * deleteXcx(id) {
    yield api.xcxDelete(id);
    yield this.query();
  }

  * getDict(dictId) {
    return yield api.getDict(dictId);
  }

  * updateEnable(data) {
    const { enable } = data;
    yield api.update({ ...data, enable: !enable });
    yield this.query();
  }

  * getCity() {
    const res = yield api.getCity('region');
    this.city = res.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
  }

  * getCcCity(args) {
    try {
      const res = yield api.getCcCity(args);
      const mapRes = res.map((item) => ({
        label: item.name,
        value: item.itemId,
      }));
      return mapRes;
    } catch (error) {
      console.log('🚀 _ file: XcxStore.js:117 _ XcxStore _ error:', error);
    }
  }

  * getCcStation(data) {
    try {
      const station = yield api.getCcStation(data);
      const stationMap = station.map((item) => ({
        label: item.name,
        value: item.itemId,
      }));
      return stationMap;
    } catch (error) {
      console.log('🚀 _ file: XcxStore.js:130 _ XcxStore _ error:', error);
    }
  }

  * getBusCity(args) {
    const res = yield api.getBusCity(args);
    const mapRes = res.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
    return mapRes;
  }

  * getBusStation(args) {
    const station = yield api.getBusStation(args);
    // eslint-disable-next-line @iceworks/best-practices/recommend-polyfill
    const stationMap = station.flatMap((item) => item.children.map((innerItem) => ({
      label: innerItem.name,
      value: innerItem.id,
      title: innerItem.name,
    })));
    return stationMap;
  }

  * getScCity(data) {
    const station = yield api.getScCity(data);
    const stationMap = station.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
    return stationMap;
  }

  * getScStation(data) {
    const station = yield api.getScStation(data);
    const temp = station.reduce((acc, arr) => {
      return acc.concat(arr.children);
    }, []);
    const stationMap = temp.map((item) => ({
      label: item.name,
      value: item.id,
    }));
    return stationMap;
  }

  * getRsCity(data) {
    const station = yield api.getRsCity(data);
    const stationMap = station.map((item) => ({
      label: item.name,
      value: item.itemId,
    }));
    return stationMap;
  }

  * getRsStation(data) {
    const station = yield api.getRsStation(data);
    const temp = station.reduce((acc, arr) => {
      return acc.concat(arr.children);
    }, []);
    const stationMap = temp.map((item) => ({
      label: item.name,
      value: item.id,
    }));
    return stationMap;
  }

  * themeConfigTheme(id, data) {
    yield api.dictUpdate(id, data);
    yield this.query();
  }

  * dictCreate(id, data) {
    yield api.addItemId(id, data);
    yield this.query();
  }

  * dictUpdate(id, data) {
    yield api.dictUpdate(id, data);
    yield this.query();
  }

  * removeItemId(dictId, itemId) {
    yield api.removeItemId(dictId, itemId);
    yield this.query();
  }

  * getIconUrl(dictId) {
    const res = yield api.getDict(dictId);
    this.iconUrls = res.map((item) => {
      const { name, extras } = item;
      const { value } = extras?.image;
      const parse = JSON.parse(value);
      return ({
        label: name,
        value: parse[0].uid,
      });
    });
  }

  localIdx(page, size, i) {
    return page * size + i + 1;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get orderStatus() {
    return this._orderStatus;
  }

  set orderStatus(value) {
    this._orderStatus = value;
    this._args.pg.page = 0;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  updateOrAddItem(tempState, itemId, content) {
    if (tempState?.length > 0) {
      for (let i = 0; i < tempState.length; i++) {
        const element = tempState[i];
        if (element.itemId === itemId) {
          element.content = content;
        }
      }
    }
    tempState.push({ itemId, content });
  }
}
